import json
import os
from django.core.management.base import BaseCommand
from psychology_questions.models import Questionnaire, Dimension, Question


class Command(BaseCommand):
    help = '导入问卷数据到数据库'

    def add_arguments(self, parser):
        parser.add_argument('--file', type=str, help='JSON文件路径')

    def handle(self, *args, **options):
        # 如果没有指定文件，使用你提供的数据
        if options['file']:
            with open(options['file'], 'r', encoding='utf-8') as f:
                questionnaire_data = json.load(f)
        else:
            # 使用你提供的MHRSP数据
            questionnaire_data = self.get_default_data()
        for data in questionnaire_data["questionnaires"]:
            self.import_questionnaire(data)

    def get_default_data(self):
        """返回你提供的MHRSP问卷数据，包含维度信息"""
        return {
            "id": "health_MHRSP",
            "title": "小学生心理健康评定量表MHRSP",
            "description": "是一种标准化量表，专为6-12岁小学生设计，用于系统评估其心理健康状况。MHRSP心理测试量表由8部分组成，分别为学习障碍、情绪障碍、性格缺陷、社会适应障碍、品德缺陷、不良习惯、行为障碍、特种障碍。量表将从这8方面综合评定小学生心理健康状况，反映小学生学习适应性、情绪稳定性、社会适应性及行为习惯等方面的情况。量表主要适用于小学生群体，可由父母或教师根据孩子平时情况进行评定，也可由本人进行评定。",
            "subtitle": "请根据您最近一周的真实感受回答以下问题",
            "icon": "适合人群：中小学生",
            "duration": "15-18",
            "difficulty": "中等",
            "dimensions": [
                {
                    "name": "学习障碍",
                    "description": "评估学习能力和学习适应性",
                    "weight": 1.0,
                    "question_range": [1, 10]
                },
                {
                    "name": "情绪障碍",
                    "description": "评估情绪稳定性和情感调节能力",
                    "weight": 1.0,
                    "question_range": [11, 20]
                },
                {
                    "name": "性格缺陷",
                    "description": "评估性格特征和人格发展",
                    "weight": 1.0,
                    "question_range": [21, 30]
                },
                {
                    "name": "社会适应障碍",
                    "description": "评估社交能力和环境适应性",
                    "weight": 1.0,
                    "question_range": [31, 40]
                },
                {
                    "name": "品德缺陷",
                    "description": "评估品德行为和道德发展",
                    "weight": 1.0,
                    "question_range": [41, 50]
                },
                {
                    "name": "不良习惯",
                    "description": "评估行为习惯和生活习性",
                    "weight": 1.0,
                    "question_range": [51, 60]
                },
                {
                    "name": "行为障碍",
                    "description": "评估行为控制和注意力",
                    "weight": 1.0,
                    "question_range": [61, 70]
                },
                {
                    "name": "特种障碍",
                    "description": "评估特殊行为和生理功能",
                    "weight": 1.0,
                    "question_range": [71, 80]
                }
            ],
            "questions": [
                # 这里是你提供的80个问题数据...
                {"id": 1, "text": "不能正确认识字母或拼读音节。", "options": ["经常", "偶尔", "没有"]},
                {"id": 2, "text": "不能正确辨认汉字。", "options": ["经常", "偶尔", "没有"]},
                # ... 其余78个问题
            ],
            "scoring": {
                "option_scores": [2, 1, 0],  # 经常=2分，偶尔=1分，没有=0分
                "reverse_scored": []  # 如果有反向计分题目，在这里标注题号
            }
        }

    def import_questionnaire(self, data):
        # 1. 创建问卷
        questionnaire, created = Questionnaire.objects.get_or_create(
            question_id=data['id'],
            defaults={
                'name': data['title'],
                'description': data['description'],
                'sub_description': data.get('subtitle', ''),
                'person': data.get('icon', ''),
                'duration': data.get('duration', ''),
                'difficulty': data.get('difficulty', ''),
                'is_active': True
            }
        )

        if created:
            self.stdout.write(f'创建问卷: {questionnaire.name}')
        else:
            self.stdout.write(f'问卷已存在: {questionnaire.name}')

        # 2. 创建维度
        description = data.get('eval', '')
        dimensions_map = {}
        for i, dim_data in enumerate(data.get('dimensions', [])):
            dimension, created = Dimension.objects.get_or_create(
                questionnaire=questionnaire,
                name=dim_data['name'],
                defaults={
                    'description': description[i + 1]['text'],
                    'weight': dim_data.get('weight', 1.0)
                },
                list=dim_data.get('list', []),
                help=description[i + 1].get('help', '')
            )
            dimensions_map[dim_data['name']] = dimension
            if created:
                self.stdout.write(f'  创建维度: {dimension.name}')

        # 3. 创建问题
        option_scores = data.get('scoring', {}).get('option_scores', [2, 1, 0])

        for q_data in data['questions']:
            # 根据问题ID确定所属维度
            question_id = q_data['id']
            dimension = self.get_dimension_for_question(question_id, data['dimensions'], dimensions_map)

            # 构建选项配置
            options_config = []
            for i, option_text in enumerate(q_data['options']):
                options_config.append({
                    'text': option_text,
                    'score': option_scores[i] if i < len(option_scores) else 0
                })

            question, created = Question.objects.get_or_create(
                questionnaire=questionnaire,
                dimension=dimension,
                title=q_data['text'],
                defaults={
                    'question_type': 'single',  # 单选题
                    'options': options_config,
                    'is_required': True,
                    'order': question_id
                }
            )

            if created:
                self.stdout.write(f'    创建问题: {question.title[:30]}...')

        self.stdout.write(self.style.SUCCESS('问卷导入完成！'))

    def get_dimension_for_question(self, question_id, dimensions, dimensions_map):
        """根据问题ID确定所属维度"""
        for dim in dimensions:
            list = dim.get('list', [])
            if question_id in list:
                return dimensions_map[dim['name']]
        #     question_range = dim.get('question_range', [])
        #     if len(question_range) == 2 and question_range[0] <= question_id <= question_range[1]:
        #         return dimensions_map[dim['name']]
        #
        # # 如果没有找到对应维度，返回第一个维度作为默认值
        # return list(dimensions_map.values())[0]

# (base) H:\python_code1\psychology_project\psychology_project>python manage.py import_questionnnaire --file ./static/question/question_list.json
